from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import request

from info import constants, db
from info.models import News, Category, User
from info.response_code import RET
from info.utils.commons import user_login_data
from info.utils.image_storage import image_storage
from . import user
from flask import render_template


@user.route('/other_news_list')
def other_news_list():
    """
    分页获取作者下的新闻信息
    1.获取参数
    2.参数转化
    3.分页查询
    4.拼接参数
    5.返回
    :return:
    """
    # 1.获取参数
    page = request.args.get('p', 1)
    author_id = request.args.get('user_id')

    # 2.参数转化
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    if not author_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数异常')

    # 3.分页查询
    try:
        paginate = News.query.filter(News.user_id == author_id).paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT,
                                                                         False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    # 4.拼接参数
    news_list = []
    for item in paginate.items:
        news_list.append(item.to_dict())

    data = {
        'current_page': paginate.page,
        'total_page': paginate.pages,
        'news_list': news_list
    }
    # 5.返回
    return jsonify(errno=RET.OK,errmsg='查询成功',data=data)


# 请求路径: /user/other
# 请求方式: GET
# 请求参数:id
# 返回值: 渲染other.html页面,字典data数据

@user.route('/other')
@user_login_data
def other():
    """
    显示作者首页
    1.获取参数
    2.校验参数
    3.获取作者信息
    4.判断用户是否关注作者
    5.返回响应
    :return:
    """
    if not g.user:
        return jsonify(errno=RET.NODATA, errmsg='用户为登陆')

    # 1.获取参数
    author_id = request.args.get('author_id')

    # 2.校验参数
    if not author_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数异常')

    # 3.获取作者信息
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    if not author:
        return jsonify(errno=RET.NODATA, errmsg='获取作者信息失败')

    # 4.判断用户是否关注作者
    is_followed = False
    if g.user in author.followers:
        is_followed = True

    # 5.返回响应
    data = {
        'userInfo': g.user.to_dict() if g.user else '',
        'author': author.to_dict(),
        'is_followed': is_followed
    }

    return render_template('news/other.html', data=data)


@user.route('/user_follow', )
@user_login_data
def user_follow():
    """
    我的关注
    1.获取参数
    2.参数类型转化
    3.根据用户获取用户关注的作者
    4.返回
    :return:
    """
    # 获取参数
    page = request.args.get('p', 1)

    # 类型转化
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    try:
        paginate = g.user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询关注作者失败')

    # 校验关注的人是否存在
    if not paginate:
        return jsonify(errno=RET.NODATA, errmsg='获取关注列表失败')

    followed_list = []

    for followed in paginate.items:
        followed_list.append(followed.to_dict())

    data = {
        'currentPage': paginate.page,
        'totalPage': paginate.pages,
        'followed_list': followed_list
    }
    return render_template('news/user_follow.html', data=data)


@user.route('/news_list')
@user_login_data
def news_list():
    """
    获取用户所有发布的新闻列表

    1.获取参数
    2.参数类型转换
    3.分页查询
    4.拼接
    5.返回数据
    :return:
    """
    # 获取参数
    page = request.args.get('p', 1)

    # 类型转化
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 分页查询
    try:
        paginate = g.user.news_list.paginate(page, constants.HOME_PAGE_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    # 拼接参数
    news_list = []
    for item in paginate.items:
        news_list.append(item.to_review_dict())

    data = {
        'totalPage': paginate.pages,
        'currentPage': paginate.page,
        'news_list': news_list
    }

    return render_template('news/user_news_list.html', data=data)


@user.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    """
    发布新闻
    1.获取参数
    2.校验非空
    3.文件上传
    4.创建新闻对象
    5.保存
    6.返回
    :return:
    """
    if request.method == "GET":
        category_list = Category.query.filter(Category.id != 1).all()
        return render_template('news/user_news_release.html', category_list=category_list)

    # 1.获取参数
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    content = request.form.get('content')
    index_image = request.files.get('index_image')

    # 2.校验非空
    if not all([title, category_id, digest, content, index_image]):
        return jsonify(errno=RET.PARAMERR, errmsg='内容没有填写完整！')

    # 3.文件上传
    try:
        img_name = image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='七牛云上传失败')

    # 判断文件是否上传成功
    if not img_name:
        return jsonify(errno=RET.NODATA, errmsg='头像上传失败！')

    # 4.创建新闻对象
    news = News()
    news.title = title
    news.user_id = g.user.id
    news.category_id = category_id
    news.content = content
    news.digest = digest
    news.source = '个人发布'
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + img_name
    news.status = 1

    # 5.保存
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='发布新闻失败')

    # 6.返回
    return jsonify(errno=RET.OK, errmsg='新闻发布成功！')


@user.route('/collection')
@user_login_data
def collection():
    """
    1.获取参数
    2.转化参数
    3.查询分页对象
    4.凭借参数
    5.返回结果
    :return:
    """

    # 获取参数
    page = request.args.get('p', 1)

    # 转换参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 查询
    try:
        paginate = g.user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    news_list = []
    for news in paginate.items:
        news_list.append(news.to_dict())

    # 拼接数据
    data = {
        'totalPage': paginate.pages,
        'currentPage': paginate.page,
        'news_list': news_list
    }
    # 返回
    return render_template('news/user_collection.html', data=data)


@user.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    """
    修改密码
    1.获取参数
    2.校验参数 非空
    3.判断原始密码是否正确
    4.修改用户密码
    :return:
    """

    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    # 获取参数
    new_password = request.json.get('old_password')
    new_password2 = request.json.get('new_password2')

    # 校验非空
    if not all([new_password, new_password2]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完出')

    # 校验密码是否正确
    if not g.user.check_passowrd(new_password):
        return jsonify(errno=RET.DATAERR, errmsg='用户密码错误')

    g.user.password = new_password2

    return jsonify(errno=RET.OK, errmsg='密码修改成功！')


@user.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    """
    修改用户头像

    1.获取参数
    2.校验参数
    3.上传图片
    4.校验图片是否上传成功
    5.修改用户的图片地址sdad
    6.返回
    :return:
    """
    if request.method == "GET":
        return render_template('news/user_pic_info.html', userInfo=g.user.to_dict())

    # 获取参数
    pic_file = request.files.get('avatar')

    # 校验非空
    if not pic_file:
        return jsonify(errno=RET.PARAMERR, errmsg='参数不存咋')

    # 上传图片
    try:
        # 读取图片文件
        img_name = image_storage(pic_file.read())

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='七牛云上传失败')

    # 校验图片是否上传成功
    if not img_name:
        return jsonify(errno=RET.NODATA, errmsg='头像上传失败')

    # 修改用户头像
    g.user.avatar_url = img_name

    return jsonify(errno=RET.OK, errmsg='头像上传成功！',
                   data={'avatar_url': constants.QINIU_DOMIN_PREFIX + g.user.avatar_url})


@user.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    """
    修改用户基本信息
    1.获取参数
    2.校验参数 非空校验
    3.对性别做判断
    4.修改用户信息
    5.更新数据
    6.返回

    :return:
    """

    # 判断请求方式
    if request.method == 'GET':
        return render_template('news/user_base_info.html', userInfo=g.user)

    # 1.获取参数
    signature = request.json.get('signature')
    nick_name = request.json.get('nick_name')
    gender = request.json.get('gender')

    # 2.校验参数 非空校验
    if not all([signature, nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')

    # 3.对性别做判断
    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg='性别选择有误')

    # 4.修改用户信息
    g.user.nick_name = nick_name
    g.user.gender = gender
    g.user.signature = signature

    # 6.返回
    return jsonify(errno=RET.OK, errmsg='修改成功！')


@user.route('/info')
@user_login_data
def user_info():
    if not g.user:
        return redirect('/')
    data = {
        'userInfo': g.user.to_dict() if g.user else ''
    }
    return render_template('news/user.html', data=data)
